package com.ruoyi.project.modules.processBranchCondition.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.modules.interfaceinfo.domain.VirtualUsage;
import com.ruoyi.project.modules.interfaceinfo.service.IVirtualUsageService;
import com.ruoyi.project.modules.parameter.domain.InterfaceParamsFieldRelation;
import com.ruoyi.project.modules.parameter.domain.Params;
import com.ruoyi.project.modules.parameter.domain.ParamsFieldRelation;
import com.ruoyi.project.modules.parameter.service.IInterfaceParamsFieldRelationService;
import com.ruoyi.project.modules.parameter.service.IParamsFieldRelationService;
import com.ruoyi.project.modules.parameter.service.IParamsService;
import com.ruoyi.project.modules.processBranch.service.impl.ProcessBranchServiceImpl;
import com.ruoyi.project.modules.processBranchConditionDetail.domain.ProcessBranchConditionDetail;
import com.ruoyi.project.modules.processBranchConditionDetail.service.IProcessBranchConditionDetailService;
import com.ruoyi.project.modules.table.domain.FieldInfo;
import com.ruoyi.project.modules.table.service.ITableInfoService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.project.modules.processBranchCondition.domain.ProcessBranchCondition;
import com.ruoyi.project.modules.processBranchCondition.service.IProcessBranchConditionService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 分支条件Controller
 * 
 * @author smallrain
 * @date 2022-04-02
 */
@Controller
@RequestMapping("/processBranchCondition/processBranchCondition")
public class ProcessBranchConditionController extends BaseController
{
    private String prefix = "processBranchCondition/processBranchCondition";

    @Autowired
    private IProcessBranchConditionService processBranchConditionService;

    @RequiresPermissions("processBranchCondition:processBranchCondition:view")
    @GetMapping()
    public String processBranchCondition()
    {
        return prefix + "/processBranchCondition";
    }

    /**
     * 查询分支条件列表
     */
    @RequiresPermissions("processBranchCondition:processBranchCondition:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ProcessBranchCondition processBranchCondition)
    {
        startPage();
        List<ProcessBranchCondition> list = processBranchConditionService.selectProcessBranchConditionList(processBranchCondition);
        return getDataTable(list);
    }

    /**
     * 导出分支条件列表
     */
    @RequiresPermissions("processBranchCondition:processBranchCondition:export")
    @Log(title = "分支条件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ProcessBranchCondition processBranchCondition)
    {
        List<ProcessBranchCondition> list = processBranchConditionService.selectProcessBranchConditionList(processBranchCondition);
        ExcelUtil<ProcessBranchCondition> util = new ExcelUtil<ProcessBranchCondition>(ProcessBranchCondition.class);
        return util.exportExcel(list, "分支条件数据");
    }

    /**
     * 新增分支条件
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存分支条件
     */
    @RequiresPermissions("processBranchCondition:processBranchCondition:add")
    @Log(title = "分支条件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ProcessBranchCondition processBranchCondition)
    {
        return toAjax(processBranchConditionService.insertProcessBranchCondition(processBranchCondition));
    }

    /**
     * 修改分支条件
     */
    @GetMapping("/edit/{branchConditionId}")
    public String edit(@PathVariable("branchConditionId") Long branchConditionId, ModelMap mmap)
    {
        ProcessBranchCondition processBranchCondition = processBranchConditionService.selectProcessBranchConditionByBranchConditionId(branchConditionId);
        mmap.put("processBranchCondition", processBranchCondition);
        return prefix + "/edit";
    }

    /**
     * 修改保存分支条件
     */
    @RequiresPermissions("processBranchCondition:processBranchCondition:edit")
    @Log(title = "分支条件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ProcessBranchCondition processBranchCondition)
    {
        return toAjax(processBranchConditionService.updateProcessBranchCondition(processBranchCondition));
    }

    /**
     * 删除分支条件
     */
    @RequiresPermissions("processBranchCondition:processBranchCondition:remove")
    @Log(title = "分支条件", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(processBranchConditionService.deleteProcessBranchConditionByBranchConditionIds(ids));
    }

    @Autowired
    private IProcessBranchConditionDetailService processBranchConditionDetailService;
    @Autowired
    private IVirtualUsageService virtualUsageService;
    @Autowired
    private IInterfaceParamsFieldRelationService interfaceParamsFieldRelationService;
    @Autowired
    private IParamsFieldRelationService paramsFieldRelationService;
    @Autowired
    private ITableInfoService tableInfoService;
    @Autowired
    private IParamsService paramsService;
    @Resource
    private ISysDictTypeService sysDictTypeService;

    @GetMapping("/refreshDescription")
    public AjaxResult refreshDescription() {

        List<SysDictData> judge_condition = this.sysDictTypeService.selectDictDataByType("JUDGE_CONDITION");
        Map<String, List<SysDictData>> collect = judge_condition.stream().collect(Collectors.groupingBy(SysDictData::getDictValue));
        List<ProcessBranchCondition> processBranchConditions = this.processBranchConditionService.selectProcessBranchConditionList(new ProcessBranchCondition());
        for (ProcessBranchCondition branchCondition : processBranchConditions) {
            if (!"else".equals(branchCondition.getType())) {
                ProcessBranchConditionDetail processBranchConditionDetail1 = new ProcessBranchConditionDetail();
                processBranchConditionDetail1.setBranchConditionId(branchCondition.getBranchConditionId());
                List<ProcessBranchConditionDetail> processBranchConditionDetailList = this.processBranchConditionDetailService.selectProcessBranchConditionDetailList(processBranchConditionDetail1);
                Map<String, List<ProcessBranchConditionDetail>> record = new TreeMap<>();
                for (ProcessBranchConditionDetail processBranchConditionDetail : processBranchConditionDetailList) {
                    List<ProcessBranchConditionDetail> processBranchConditionDetails = record.computeIfAbsent(processBranchConditionDetail.getBranchConditionGroupId(), key -> new ArrayList<>());
                    processBranchConditionDetails.add(processBranchConditionDetail);
                }
                String conditionName = "", branchConditionDescription = "";
                String joinCondition = " " + branchCondition.getJoinCondition() + " ";
                for (Map.Entry<String, List<ProcessBranchConditionDetail>> stringListEntry : record.entrySet()) {
                    List<ProcessBranchConditionDetail> details = stringListEntry.getValue();
                    for (int i = 0; i < details.size(); i++) {
                        ProcessBranchConditionDetail detail = details.get(i);
                        VirtualUsage virtualUsage = new VirtualUsage();
                        virtualUsage.setId(detail.getInterfaceId());
                        List<VirtualUsage> virtualUsages = this.virtualUsageService.selectVirtualUsages(virtualUsage);
                        String interfaceName = virtualUsages.get(0).getSlaveInterfaceName();
                        String objectFieldName = detail.getObjectFieldName();
                        String objectName = detail.getObjectName();
                        if (detail.getObjectType().equals("3")) {
                            InterfaceParamsFieldRelation interfaceParamsFieldRelation = this.interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(detail.getParamsId());
                            Params params = this.paramsService.selectParamsById(interfaceParamsFieldRelation.getObjectId());
                            objectName = params.getZhName();
                            ParamsFieldRelation paramsFieldRelation = this.paramsFieldRelationService.selectParamsFieldRelationById(detail.getObjectId());
                            List<FieldInfo> fieldInfoList = this.tableInfoService.selectFieldInfoByFieldId(Arrays.asList(paramsFieldRelation.getFieldId()));
                            objectFieldName = fieldInfoList.get(0).getFieldName();
                        } else {
                            InterfaceParamsFieldRelation interfaceParamsFieldRelation = this.interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(detail.getObjectId());
                            if (detail.getObjectType().equals("1")) {
                                List<FieldInfo> fieldInfoList = this.tableInfoService.selectFieldInfoByFieldId(Arrays.asList(interfaceParamsFieldRelation.getObjectId()));
                                objectName = fieldInfoList.get(0).getFieldName();
                            } else {
                                Params params = this.paramsService.selectParamsById(interfaceParamsFieldRelation.getObjectId());
                                objectName = params.getZhName();
                            }
                        }

                        conditionName = conditionName + interfaceName + "." + objectName;
                        if (detail.getBranchConditionDetailDictCode().equals("1")) {
                            if (StringUtils.isNotEmpty(objectFieldName)) {
                                conditionName = conditionName + "." + objectFieldName;
                            }
                        } else {
                            conditionName = conditionName + "数据集条数";
                        }
                        if ("IS_NULL".equals(detail.getJudgeConditionDictCode())) {
                            conditionName = conditionName + ProcessBranchServiceImpl.convertDict("IS_NULL", collect);
                        } else if ("IS_NOT_NULL".equals(detail.getJudgeConditionDictCode())) {
                            conditionName = conditionName + ProcessBranchServiceImpl.convertDict("IS_NOT_NULL", collect);
                        } else if ("IS_TRUE".equals(detail.getJudgeConditionDictCode())) {
                            conditionName = conditionName + ProcessBranchServiceImpl.convertDict("IS_TRUE", collect);
                        } else if ("IS_FALSE".equals(detail.getJudgeConditionDictCode())) {
                            conditionName = conditionName + ProcessBranchServiceImpl.convertDict("IS_FALSE", collect);
                        } else {
                            conditionName = conditionName + ProcessBranchServiceImpl.convertDict(detail.getJudgeConditionDictCode(), collect) + (StringUtils.isNotEmpty(detail.getDictName()) ? detail.getDictName() : detail.getContractValue());
                        }
                        if (i == details.size() - 1) continue;
                        conditionName = conditionName + " " + detail.getJoinCondition() + " ";
                    }

                    if (details.size() > 1) {
                        conditionName = "(" + conditionName + ")";
                    }
                    branchConditionDescription = branchConditionDescription + conditionName + joinCondition;
                }
                String substring = branchConditionDescription.substring(0, branchConditionDescription.length() - joinCondition.length());
                branchCondition.setBranchConditionDesc("如果" + substring + " 执行下一步");
                this.processBranchConditionService.updateProcessBranchCondition(branchCondition);
            }
        }
        return success();
    }
}
